
#include <stdio.h>
#include "msg_adapter.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "softbus_tool/transmission.h"
#include "utils_log.h"

QueueHandle_t   g_queSoftBusRec = NULL;
#define RECV_QUEUE_NUM  8           //队列项的个数
#define RECV_QUEUE_SIZE (1024)        //每个队列项的最大数据长度


//软总线数据接收回调函数
static void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen)
{
    if(NULL==data || NULL==g_queSoftBusRec ) { return; }

    if(dataLen > RECV_QUEUE_SIZE) {
        printf("[%s-%d]:dataLen is too long\n", __func__, __LINE__);
        LOG_TO_FILE("dataLen is too long");
        return;
    }
    
    if(xQueueSendToBack(g_queSoftBusRec, data, 0xff) == pdTRUE ){
        printf("[%s-%d]:xQueueSendToBack ok\n", __func__, __LINE__);  
    }else{
        char null_buf[RECV_QUEUE_SIZE] = {0};
        xQueueReceive(g_queSoftBusRec, null_buf, 0);     
    }//
    
    printf("\n>>>OnMessageReceived sessionId = %d, data = %s \n", sessionId, (const char *)data);
}

static IKHSessionCallback g_callback = {
    .OnBytesReceived = OnMessageReceived,
    .OnMessageReceived = OnMessageReceived,
    .OnStreamReceived = OnMessageReceived,
};

int InitMsgQueue(void)
{
    if(NULL != g_queSoftBusRec){
       printf("[%s-%d]:---g_queSoftBusRec != NULL---\r\n", __func__, __LINE__);
       return 0;
    }//

    g_queSoftBusRec = xQueueCreate(RECV_QUEUE_NUM, RECV_QUEUE_SIZE);
    if(NULL == g_queSoftBusRec){
        printf("[%s-%d]:---Create g_queSoftBusRec err---\r\n", __func__, __LINE__);
        LOG_TO_FILE("Create g_queSoftBusRec err");
        return  -1;
    }else{
        printf("[%s-%d]:---Create g_queSoftBusRec ok---\r\n", __func__, __LINE__);
    }//

    RegisterSessionCallback(&s);

    return 0;
}

void DestroyMsgQueue(void)
{
    if(NULL == g_queSoftBusRec) { return; }

    vQueueDelete(g_queSoftBusRec);
    g_queSoftBusRec = NULL;   
}

int RecvMsg(uint8_t *msg, int len)
{   
    if(NULL == msg) { 
        printf("[%s-%d]: msg is NULL\n", __func__, __LINE__);
        LOG_TO_FILE("msg is NULL");
        return -1; 
    }

    if(NULL == g_queSoftBusRec){
        printf("[%s-%d]: g_queSoftBusRec is NULL\n", __func__, __LINE__);
        LOG_TO_FILE("g_queSoftBusRec is NULL");
        return  -1;
    }//

    if(len > RECV_QUEUE_SIZE){
        printf("[%s-%d]:recv len is too long\n", __func__, __LINE__);
        LOG_TO_FILE("recv len is too long");
        return  -1;
    }//

    if(xQueueReceive(g_queSoftBusRec, msg, 0) == pdTRUE){
        printf("[%s-%d]--recv msg: %s\n",__func__, __LINE__, msg);
        return  0;
    }else{
        return  -1;
    }//
}

int SendMsg(const uint8_t *msg, int len)
{
    if(NULL == msg) { 
        printf("[%s-%d]: msg is NULL\n", __func__, __LINE__);
        LOG_TO_FILE("msg is NULL");
        return -1; 
    }//

    return BirefSendBytesToAll(msg, len);
}
